<template>
  <div class="view-fill">
    <div v-show="!assetDetailInfo.visible" class="app-container-flex">
      <FullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button @click="save()">保存</el-button>
        </template>
        <div class="model-panel" v-if="!!orderId">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <PageForm
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
            </PageForm>
          </div>
        </div>
        <div class="model-panel" v-else-if="!orderId">
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <PageFilter :filter-list="filterInfo.list">
              <template v-slot:filter-removeAsset>
                <el-button :disabled="!canRemoveAsset" @click="removeAsset()"
                  >删除资产</el-button
                >
              </template>
              <template v-slot:filter-assetCodeScan>
                <ScanInputBox
                  :query="scanInfo.query"
                  :api="scanInfo.api"
                  @callback="onCallBackScanData"
                />
              </template>
            </PageFilter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <PageTable
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isRowClickSelect="true"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-estimateTreatPersonTime="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.estimateTreatPersonTime`"
                      :rules="[
                        {
                          required: true,
                          message: '请输入预计检查(治疗)人次/月',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.estimateTreatPersonTime"
                        clearable
                        controls-position="right"
                        :min="0"
                        :max="99999"
                        :precision="0"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.estimateTreatPersonTime`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-estimateTreatIncome="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.estimateTreatIncome`"
                      :rules="[
                        {
                          validator: $validate.positiveMoneyAsset,
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.estimateTreatIncome"
                        clearable
                        controls-position="right"
                        :precision="
                          $store.state.permission.systemConfig
                            .assets_price_precision
                        "
                        :min="0"
                        :max="999999999999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.estimateTreatIncome`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-estimatePowerUp="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.estimatePowerUp`"
                      :rules="[
                        {
                          required: true,
                          message: '请输入预计开机时长/月',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.estimatePowerUp"
                        clearable
                        controls-position="right"
                        :min="0"
                        :max="99999"
                        :precision="0"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.estimatePowerUp`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                </PageTable>
              </el-form>
            </div>
          </div>
        </div>
      </FullScreen>
    </div>
    <!-- 添加资产 -->
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      table-key="addCoreAsset-com.slip.spd.entity.vo.core.CoreAssetVO"
      :check-box="true"
      :highlightRow="true"
      @callback="callBackAsset"
    />
    <!-- 详情页 -->
    <AssetCardDetail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
    />
  </div>
</template>

<script setup name="assetAnalysisModify">
import {
  batchInsertAssetAnalysis,
  updateAssetAnalysis,
  getAssetAnalysisById,
  scanAssetAnalysis,
} from '@/api/asset'
import AssetCardDetail from '@/views/asset/assetManage/assetCard/details'

const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title', 'orderId'])

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const scanInfo = ref({
  query: {},
  api: scanAssetAnalysis,
})
//表单相关
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '资产名称',
      value: 'assetName',
      type: 'input',
      disabled: true,
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'input',
      disabled: true,
    },

    {
      label: '规格',
      value: 'standard',
      type: 'input',
      disabled: true,
    },
    { label: '厂家', value: 'brandName', type: 'input', disabled: true },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'input',
      disabled: true,
    },
    {
      label: '仓库',
      value: 'depotName',
      type: 'input',
      disabled: true,
    },
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '管理部门',
      value: 'manageDeptName',
      type: 'input',
      disabled: true,
    },
    { label: '位置', value: 'location', type: 'input', disabled: true },
    {
      label: '预计检查(治疗)人次/月',
      value: 'estimateTreatPersonTime',
      type: 'number',
      max: 99999,
    },
    {
      label: '预计检查(治疗)收入/月',
      value: 'estimateTreatIncome',
      type: 'number',
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
      max: 999999999999999,
    },
    {
      label: '预计开机时长/月',
      value: 'estimatePowerUp',
      type: 'number',
      max: 99999,
    },
  ],
  rules: {
    estimateTreatPersonTime: [
      {
        required: true,
        message: '请输入预计检查(治疗)人次/月',
        trigger: ['change', 'blur'],
      },
    ],
    estimateTreatIncome: [
      {
        required: true,
        message: '请输入预计检查(治疗)收入/月',
        trigger: ['change', 'blur'],
      },
      {
        validator: proxy.$validate.positiveMoneyAsset,
        trigger: ['blur', 'change'],
      },
    ],
    estimatePowerUp: [
      {
        required: true,
        message: '请输入预计开机时长/月',
        trigger: ['change', 'blur'],
      },
    ],
  },
  labelWidth: '180px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {},
  list: [
    { type: 'button', label: '添加资产', event: addAsset },
    { type: 'slot', value: 'removeAsset' },
    { type: 'slot', value: 'assetCodeScan' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '资产卡片号',
      value: 'assetCode',
    },
    {
      label: '资产名称',
      value: 'assetName',
    },
    { label: '规格', value: 'standard' },
    { label: '厂家', value: 'brandName' },
    { label: '供应商', value: 'supplierName' },
    { label: '仓库', value: 'depotName' },
    { label: '使用部门', value: 'useDeptName' },
    { label: '管理部门', value: 'manageDeptName' },
    { label: '位置', value: 'location' },
    {
      label: '预计检查(治疗)人次/月',
      value: 'estimateTreatPersonTime',
      type: 'slot',
      width: '180px',
    },
    {
      label: '预计检查(治疗)收入/月',
      value: 'estimateTreatIncome',
      type: 'slot',
      width: '180px',
    },
    {
      label: '预计开机时长/月',
      value: 'estimatePowerUp',
      type: 'slot',
      width: '180px',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeAsset,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const selectAssetInfo = ref({
  visible: false,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      assetStatus: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '1,3',
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '3',
      },
    },
    queryParams: {
      assetAnalysisFilter: 1,
    },
  },
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
  title: '资产详情',
})
const selectDepotInfo = ref({
  visible: false,
  query: {
    // depotAuth: 'id',
    status: 1,
    useTypeId: 2,
    idNot: '',
  },
})
const selectExportDepotInfo = ref({
  visible: false,
  query: {
    // depotAuth: 'id',
    status: 1,
    useTypeId: 2,
    idNot: '',
  },
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveAsset = computed(() => {
  return tableInfo.value.selections.length
})
function getMain() {
  getAssetAnalysisById(props.orderId).then((res) => {
    if (res && res.success) {
      formInfo.value.data = res.data
    }
  })
}
function changeValidate(value, str, ref) {
  setTimeout(() => {
    proxy.$refs[ref].clearValidate(str)
  }, 30)
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}

// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function save() {
  if (props.orderId) {
    //修改

    formInfo.value.ref.validate((valid) => {
      if (valid) {
        updateAssetAnalysis(formInfo.value.data).then((res) => {
          if (res && res.success) {
            showDialog.value = false
            proxy.$emit('returnModify', false)
          }
        })
      }
    })
  } else {
    //新增
    if (tableInfo.value.data && tableInfo.value.data.length === 0) {
      proxy.$message.warning('请添加资产！')
      return
    }
    proxy.$refs.tableForm.validate((valid) => {
      if (valid) {
        batchInsertAssetAnalysis(tableInfo.value.data).then((res) => {
          if (res && res.success) {
            showDialog.value = false
            proxy.$emit('returnModify', false)
          }
        })
      }
    })
  }
}

//选择资产
function addAsset() {
  if (tableInfo.value.data.length) {
    selectAssetInfo.value.query.queryMap.id.value = tableInfo.value.data
      .map((item) => item.assetId)
      .toString()
  } else {
    selectAssetInfo.value.query.queryMap.id.value = ''
  }
  selectAssetInfo.value.visible = true
}
function onCallBackScanData(data, callback) {
  if (data && data.assetCode) {
    data.assetId = data.id
    if (tableInfo.value.data) {
      tableInfo.value.data.forEach((item) => {
        item.isChoice = false
      })
      let index = tableInfo.value.data.findIndex(
        (item) => item.assetCode === data.assetCode
      )
      if (index !== -1) {
        callback(true)
      } else {
        tableInfo.value.data.unshift(data)
        callback(false)
      }
    } else {
      tableInfo.value.data.unshift(data)
      callback(true)
    }
  }
}
function callBackAsset(data) {
  data.forEach((item) => {
    item.assetId = item.id
  })
  tableInfo.value.data = data.concat(tableInfo.value.data)
}
//删除资产
function removeAsset(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
onMounted(() => {
  if (props.orderId) {
    getMain()
  }
})
</script>

<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow: hidden;
}
</style>
